<template>
 <div>
   <div class="order-header">
     <el-form :inline="true" >
       <el-form-item v-if="hasAuth('order:list')">按信息搜索</el-form-item>
       <el-form-item v-if="hasAuth('order:list')">
         <el-input :placeholder="searchType" v-model="search" class="input-with-select"
                   @change="changeSearchInput"
                   :clearable=true>
           <el-select v-model="searchType" slot="prepend" placeholder="请选择">
             <el-option label="订单编号" value="order_no"></el-option>
             <el-option label="姓名" value="order_name"></el-option>
             <el-option label="电话号码" value="order_phone"></el-option>
           </el-select>
           <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
         </el-input>
       </el-form-item>

       <el-form-item>
         <el-button type="primary" v-if="hasAuth('order:add')" @click="editOrder(null)">新增订单</el-button>
       </el-form-item>

       <el-form-item v-if="hasAuth('order:update')">
         <el-popover
             placement="right"
             v-model="showBatchOrderCard"
             width="180">
           <p style="color: red">确定批量{{OkOrRight}}这些订单吗？</p>
           <div style="text-align: right; margin: 0">
             <el-button size="mini" type="text" @click="showBatchOrderCard = false;">取消</el-button>
             <el-button type="primary" size="mini"
                        @click="showBatchOrderCard = false;batchHandle(OkOrRight==='确认'?'right':'ok')">确定</el-button>
           </div>
           <el-button type="danger" slot="reference" v-show="!showOkOrRightButton">批量{{OkOrRight}}</el-button>
         </el-popover>
       </el-form-item>

       <el-form-item v-if="hasAuth('order:delete')">
         <el-popover
             placement="right"
             v-model="showBatchDeleteCard"
             width="180">
           <p style="color: red">确定批量删除这些订单吗？</p>
           <div style="text-align: right; margin: 0">
             <el-button size="mini" type="text" @click="showBatchDeleteCard = false;">取消</el-button>
             <el-button type="primary" size="mini"  @click="showBatchDeleteCard = false;batchHandle('delete')">确定</el-button>
           </div>
           <el-button type="danger" slot="reference" v-show="!showBatchDeleteButton">批量删除</el-button>
         </el-popover>
       </el-form-item>
     </el-form>
   </div>

   <el-table
       v-if="hasAuth('order:list')"
       :data="orderList" ref="orderList" border :fit="true"
       @selection-change="selectionChange" style="width: 100%">
     <el-table-column
         type="selection"
         width="55">
     </el-table-column>
     <el-table-column
         fixed
         prop="orderNo"
         label="订单编号"
         width="155">
     </el-table-column>
     <el-table-column
         label="订单状态"
         width="100"
         :filters="[{ text: '已取消', value: 0 }, { text: '待付款', value: 1 }, { text: '已付款', value: 2 }
         , { text: '待确认', value: 3 }, { text: '已确认', value: 4 }, { text: '已入住', value: 5 }, { text: '待评论', value: 6 }
         , { text: '已完成', value: 7 }, { text: '待退款', value: 8 }, { text: '已退款', value: 9 }, { text: '错误', value: 10 }]"
         :filter-method="filterStatueTag"
         filter-placement="bottom-end">
       <template slot-scope="scope">
         <el-tag :type="orderStatue[scope.row.orderStatue].type">{{orderStatue[scope.row.orderStatue].statue}}</el-tag>
       </template>
     </el-table-column>
     <el-table-column
         prop="orderRealPrice"
         label="实付金额"
         width="80">
     </el-table-column>
     <el-table-column
         prop="orderName"
         label="姓名"
         width="130">
     </el-table-column>
     <el-table-column
         prop="orderRoomNo"
         label="房间编号"
         width="100">
     </el-table-column>
     <el-table-column
         label="电话"
         width="150">
       <template slot-scope="scope">
         <el-popover trigger="hover" placement="top">
           <span>用户邮箱：{{scope.row.orderEmail}}</span><br>
           <div slot="reference" class="name-wrapper">
             {{ scope.row.orderPhone }}
           </div>
         </el-popover>
       </template>
     </el-table-column>
     <el-table-column
         prop="orderComment"
         label="订单评论"
         width="200"
         show-overflow-tooltip>
     </el-table-column>
     <el-table-column
         prop="orderNote"
         label="订单备注"
         empty-text="无"
         width="200"
         show-overflow-tooltip>
     </el-table-column>
     <el-table-column
         label="创建订单时间"
         show-overflow-tooltip>
       <template slot-scope="scope">
         <el-popover trigger="hover" placement="top">
           <span>付款时间：{{scope.row.orderFkTime}}</span><br>
           <span>确认时间：{{scope.row.orderOkTime}}</span><br>
           <span>取消时间：{{scope.row.orderCancerTime}}</span><br>
           <span>自动确认时间：{{scope.row.orderAutoTime}}</span>
           <div slot="reference" class="name-wrapper">
             {{ scope.row.createTime }}
           </div>
         </el-popover>
       </template>
     </el-table-column>
     <el-table-column
         v-if="hasAuth('order:update')"
         fixed="right"
         label="操作"
         width="60">
       <template slot-scope="scope">
         <el-button @click="editOrder(scope.row)" type="text" size="small">编辑</el-button>
       </template>
     </el-table-column>
   </el-table>
   <div class="page" v-if="hasAuth('order:list')">
     <el-pagination
         @size-change="orderPageSizeChange"
         @current-change="orderPageCurrentChange"
         :current-page="current"
         :page-sizes="[5, 10, 20, 30, 999]"
         :page-size="size"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
     </el-pagination>
   </div>

   <!--编辑 新增 订单-->
   <el-dialog
       title="订单操作"
       :visible.sync="editOrderShow"
       :close-on-click-modal="false"
       width="45%"
       center
       :before-close="editOrderClose">
     <el-form ref="orderForm" :rules="orderRules" :model="order" label-width="auto">
       <el-row>
         <el-col :span="12">
           <el-form-item label="订单编号">
             <el-input :value="EditOrAddFlag?'订单id自动生成':order.orderNo" disabled></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="订单状态">
             <el-select v-model="order.orderStatue" placeholder="订单状态"
                        v-if="!EditOrAddFlag" style="width: 100%">
               <el-option
                   v-for="(item,index) in orderStatue"
                   :key="index.value"
                   :label="item.statue"
                   :value="index">
               </el-option>
             </el-select>
             <el-input v-model="orderStatue[4].statue" disabled v-else></el-input>
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="用户姓名" prop="orderName">
             <el-input v-model="order.orderName" ></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="用户电话" prop="orderPhone">
             <el-input v-model="order.orderPhone" ></el-input>
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="用户邮箱">
             <el-input v-model="order.orderEmail" type="email" ></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="付款金额" prop="orderRealPrice">
             <el-input v-model="order.orderRealPrice"></el-input>
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="房间类型" prop="orderRoomTypeId">
             <el-select v-model="order.orderRoomTypeId" filterable placeholder="请选择" style="width: 100%"
                        :disabled="order.orderStatue===3 ">
               <el-option
                   v-for="item in roomTypeInfo" :key="item.id" :label="item.roomInfo"
                   :value="item.id">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="6">
           <el-form-item label="房间编号" prop="orderRoomNo">
             <el-select v-model="order.orderRoomNo" filterable placeholder="请选择" style="width: 100%"
                        >
               <el-option
                   v-for="item in roomNos" :key="item" :label="item" :value="item">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="6">
           <el-form-item label="房间详情">
             <el-button icon="el-icon-search" circle @click="getRoomDetail(order.orderRoomNo)"></el-button>
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12">
         </el-col>
         <el-col :span="12">
           <el-form-item label="订单评分" v-if="!EditOrAddFlag && order.orderStatue === 7" prop="orderScore">
             <el-input-number v-model="order.orderScore" :precision="2"
                              :step="0.1" :max="5" :min="0" style="width: 100%"
             ></el-input-number>
           </el-form-item>
         </el-col>
       </el-row>
       <el-form-item label="订单评论" v-if="!EditOrAddFlag && order.orderStatue === 7" prop="orderComment">
         <el-input v-model="order.orderComment" ></el-input>
       </el-form-item>
       <el-form-item label="退款原因" v-if="order.orderStatue === 8||order.orderStatue === 9" prop="orderCancerReason">
         <el-input v-model="order.orderCancerReason" ></el-input>
       </el-form-item>
       <el-form-item label="订单备注">
         <el-input v-model="order.orderNote" ></el-input>
       </el-form-item>
     </el-form>
     <span slot="footer" class="dialog-footer">
        <el-button @click="editOrderClose">取 消</el-button>
        <el-button type="primary" @click="okEditOrder">确 定</el-button>
      </span>
   </el-dialog>

  <!--显示房间详细数据-->
   <el-drawer
       title="房间数据"
       :visible="showRoomDetail"
       @close="showRoomDetail = false"
       direction="rtl">
     <el-card>
       <el-image
           style="width: 200px; height: 200px"
           :src="room.roomImages?room.roomImages.split('|')[0]:''"
           :preview-src-list="room.roomImages?room.roomImages.split('|'):[]"></el-image>
       <div>房间编号：{{room.roomNo}}</div>
       <div>房间标题：{{room.roomComment}}</div>
       <div>房间描述：{{room.roomDesc?room.roomDesc:'无'}}</div>
       <div>房间楼层：{{room.roomFloor}}楼</div>
       <div>房间名称：{{room.roomName}}</div>
     </el-card>
   </el-drawer>

   <admin-footer/>
 </div>
</template>

<script>
import {
  addOrder,
  batchHandleOrder,
  getAllOrderOrSearch,
  updateOrder
} from "@/network/order";
import {
  getFreeRoomIdsForRoomTypeId,
  getRoomByOrderRoomNo,
  getRoomTypeAndBed,
} from "@/network/room";
import AdminFooter from "@/components/conment/adminfooter/AdminFooter";
import {hasPermission} from "@/utils/mixin";
export default {
  name: "Order",
  components: {AdminFooter},
  mixins:[hasPermission],
  data() {
    const checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('订单价格不能为空'));
      }
      setTimeout(() => {
        const regx = /^\d+(\.\d{1,2})?$/; // 数字正则[?匹配0次或1次],只能输⼊两位⼩数
        if (!regx.test(value)) {
          return callback(new Error('请检查输入的价格'));
        }else {
          callback()
        }}, 500);

    };
    return {
      editOrderShow:false,
      orderList:[],
      roomTypeInfo:[],
      roomNos:[],
      order:{},
      tempOrder:{},
      EditOrAddFlag:false,
      orderStatue: [
        {'statue':'已取消','type':'info'},
        {'statue':'待付款','type':'danger'},
        {'statue':'已付款','type':'success'},
        {'statue':'待确认','type':'warning'},
        {'statue':'已确认','type':'success'},
        {'statue':'已入住','type':'success'},
        {'statue':'待评论','type':'warning'},
        {'statue':'已完成','type':'info'},
        {'statue':'待退款','type':'danger'},
        {'statue':'已退款','type':'danger'},
        {'statue':'错误','type':'danger'},
      ],//订单状态
      orderRules:{
        orderName:[
          { required: true, message: '请输入订单用户', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        orderPhone:[
          { required: true, message: '请输入订单电话', trigger: 'blur' },
          { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }
        ],
        // orderRealPrice:[
        //   { validator:checkPrice, trigger: 'blur' },
        // ],
        // orderRoomNo:[
        //   { required: true, message: '请选择房间', trigger: 'blur' },
        // ],
      },
      search:'',//搜索内容
      searchType:'order_no',//搜索类型

      showBatchDeleteButton:true,
      showOkOrRightButton:true,//显示批量按键
      selectedRows:[],
      OkOrRight:'确认',
      showBatchOrderCard:false,
      showBatchDeleteCard:false,

      showRoomDetail:false,
      room:{},

      size: 10,
      current:1,
      total:0,
    }
  },
  watch:{
    'order.orderRoomTypeId': {
      handler(newName,oldName) {
        if (oldName!==undefined&&newName!==oldName){
          getFreeRoomIdsForRoomTypeId(this.order.orderRoomTypeId).then(res=>{
            this.roomNos = res.data.data
          })
          //清除以前的选择
          this.$set(this.order,'orderRoomNo',null)
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //编辑订单 新增订单
    editOrder(row){
      if (row){
        //获取所有可用房间编号
        getFreeRoomIdsForRoomTypeId(row.orderRoomTypeId).then(res=>{
          this.roomNos = res.data.data
        })
        this.EditOrAddFlag = false
        this.order = JSON.parse(JSON.stringify(row))
        this.tempOrder = JSON.parse(JSON.stringify(row))
      }else {
        this.EditOrAddFlag = true
        this.order = {}
        this.tempOrder = {}
      }

      this.editOrderShow = true
    },
    //关闭编辑订单界面
    editOrderClose(){
      this.$refs.orderForm.clearValidate()
      this.order = {}
      this.tempOrder = {}
      this.editOrderShow = false
    },
    //确认修改 新增订单
    okEditOrder(){
      this.$refs.orderForm.validate(valid=>{
        if (valid){
          if (this.EditOrAddFlag){//添加订单
            addOrder(this.order).then(res=>{
              this.$message.success("添加成功")
              //刷新数据
              this.getOrderList(this.current,this.size,'','')
            })
          }else {//修改订单
            if (JSON.stringify(this.order) !== JSON.stringify(this.tempOrder)){//是否修改
              //如果不是退款订单 就清空退款原因
              if (this.order.orderStatue!==5&&this.order.orderStatue!==6)
                this.$set(this.order,'orderCancerReason','')
              updateOrder(this.order).then(res=>{
                this.$message.success("更新成功")
                //刷新数据
                this.getOrderList(this.current,this.size,'','')
              })
            }
          }
          this.$refs.orderList.clearFilter();//清除过滤条件
          this.editOrderClose()
        }else {
          console.log('表单验证失败')
        }
      })
    },
    //搜索数据
    searchData(){
      //数据不为空
      if (this.search!==''){
        this.getOrderList(this.current,this.size,this.searchType,this.search)
      }else {
        this.$message.warning("请输入数据后再查询")
      }
    },
    //过滤
    filterStatueTag(value, row){
      //清除选中状态
      this.$refs.orderList.clearSelection()
      return row.orderStatue === value
    },
    //如果清除了数据就更新列表
    changeSearchInput(){
      if (this.search===''){
        this.getOrderList(this.current,this.size,'','')
      }
    },
    //每页数据条数改变
    orderPageSizeChange(val){
      this.size = val
      this.getOrderList(this.current,this.size,'','')
    },
    //页数改变
    orderPageCurrentChange(val){
      this.current = val
      this.getOrderList(this.current,this.size,'','')
    },
    //批量操作订单  eg:确认 完成 删除....
    batchHandle(type){
      batchHandleOrder(type,this.selectedRows.map(res=>res.id)).then(res=>{
        this.getOrderList(this.current,this.size,'','')
        this.$message.success('操作成功')
      })
      this.afterBatchFilter()
    },
    //过滤批量操作之后
    afterBatchFilter(){
      this.$refs.orderList.clearFilter();//清除过滤条件
      this.$refs.orderList.clearSelection()//清除选中状态
    },
    //多选操作
    selectionChange(val){
      let enables = val.filter(res=>{
        return res.orderStatue === 3//筛选待确认订单
      })
      let disables = val.filter(res=>{
        return res.orderStatue === 5//筛选待完成
      })
      let ok = val.filter(res=>{
        return res.orderStatue !== 5 && res.orderStatue !== 3//筛选非待确认和非待完成订单
      })
      //全部为待完成订单 就显示待完成批量按钮
      if (Object.keys(enables).length === 0 && Object.keys(disables).length !== 0 && Object.keys(ok).length === 0){
        this.OkOrRight = '完成'
        this.showOkOrRightButton = false
      }else if (Object.keys(enables).length !== 0 && Object.keys(disables).length === 0 && Object.keys(ok).length === 0){
        this.OkOrRight = '确认'
        this.showOkOrRightButton = false//显示待确认批量按钮
      }else if(Object.keys(ok).length !== 0){//如果两中订单状态都存在 就不显示此按钮
        this.showOkOrRightButton = true
      }else {
        this.showOkOrRightButton = true
      }
      this.selectedRows = val
      //如果多选选中了订单，就显示删除批量按钮
      this.showBatchDeleteButton = this.selectedRows.length === 0
    },
    //显示房间详细信息
    getRoomDetail(orderRoomNo){
      if (orderRoomNo){
        getRoomByOrderRoomNo(orderRoomNo).then(res=>{
          this.room = res.data.data
        })
        this.showRoomDetail = true
      }else {
        this.$message.warning('请先选择房间')
      }
    },
    //订单状态如果为 完成 取消 错误 就锁定....
    getDisabled(order){
      return  order.orderStatue === 0 || order.orderStatue === 1|| order.orderStatue === 2
          || order.orderStatue === 7 || order.orderStatue === 8|| order.orderStatue === 10
    },
    //获取所有订单信息
    getOrderList(current,size,type,data){
      getAllOrderOrSearch(current,size,type,data).then(res=>{
        if (res.data.data.records.length === 0){
          this.$message.warning('数据为空')
        }
        this.orderList = res.data.data.records
        this.size = res.data.data.size
        this.current = res.data.data.current
        this.total = res.data.data.total
      })
    }
  },
  created() {
    this.getOrderList(this.current,this.size,'','')
    getRoomTypeAndBed().then(res=>{
      this.roomTypeInfo = res.data.data
    })
  }
}
</script>

<style scoped>

</style>